package schoolmath.web.services;

import liquibase.Liquibase;
import liquibase.database.Database;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.LiquibaseException;
import liquibase.logging.LogFactory;
import liquibase.logging.LogLevel;
import liquibase.resource.ClassLoaderResourceAccessor;
import org.hibernate.Session;
import org.hibernate.jdbc.Work;

import javax.inject.Inject;
import java.sql.Connection;
import java.sql.SQLException;

public class LiquiBaseConnectorImpl implements LiquiBaseConnector {

	@Inject
	private Session session;

	private void make(Connection connection) {
		LogFactory.getLogger().setLogLevel(LogLevel.WARNING);

		try {
			Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
			Liquibase liquibase = new Liquibase("/databaseChangeLog.xml", new ClassLoaderResourceAccessor(), database);
			liquibase.update(null);
		} catch (LiquibaseException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void update() {
		session.doWork(new Work() {
			@Override
			public void execute(Connection connection) throws SQLException {
				make(connection);
			}
		});
	}

}